package cc.rengu.igas.opms.core.service.trans.common;

import cc.rengu.igas.opms.common.constant.OpmsParamConstant;
import cc.rengu.igas.opms.common.enums.RespCodeEnum;
import cc.rengu.igas.opms.core.service.base.ManageService;
import cc.rengu.igas.opms.facade.base.BaseRequest;
import cc.rengu.igas.opms.facade.response.GetPublicKeyResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.CertInfoMapper;
import cc.rengu.oltp.service.common.dao.SecPlanInfoMapper;
import cc.rengu.oltp.service.common.dao.SrcChannelInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.CertInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SecPlanInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SrcChannelInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.CertInfo;
import cc.rengu.oltp.service.common.entity.SecPlanInfo;
import cc.rengu.oltp.service.common.entity.SrcChannelInfo;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 获取通信公钥
 *
 * @author keyi
 * @modify by wangcheng
 * @date 2020/3/17.
 */
public class GetPublicKeyService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        BaseRequest baseRequest = new BaseRequest();
        ConvertUtil.convertOutput(baseRequest);
        return baseRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        BizResponse<GetPublicKeyResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);

        BaseRequest baseRequest = (BaseRequest) request;
        String instId = baseRequest.getHeader().getInstId();

        //查询交易渠道信息表获取系统安全计划标识
        String srcChannelInfoKey = baseRequest.getHeader().getInstId().trim() + baseRequest.getHeader().getSrcSysId().trim() + baseRequest.getHeader().getChanlId().trim();
        rglog.debug("获取srcChannelInfo的key:<{}>", srcChannelInfoKey);
        SrcChannelInfo srcChannelInfo = JSON.parseObject(RedisUtil.hashGet(AppParamConstant.CHANNEL_ACQ_INFO_CACHE, srcChannelInfoKey), SrcChannelInfo.class);
        if (null == srcChannelInfo) {
            srcChannelInfoKey = baseRequest.getHeader().getInstId().trim() + baseRequest.getHeader().getSrcSysId().trim() + "*";
            rglog.debug("获取srcChannelInfo的key:<{}>", srcChannelInfoKey);
            srcChannelInfo = JSON.parseObject(RedisUtil.hashGet(AppParamConstant.CHANNEL_ACQ_INFO_CACHE, srcChannelInfoKey), SrcChannelInfo.class);
            if (null == srcChannelInfo) {
                SrcChannelInfoMapper srcChannelInfoMapper = new SrcChannelInfoMapperImpl();
                srcChannelInfo = srcChannelInfoMapper.selectSrcChannelInfoByPrimaryKey(txnInfo.getSrcTxnAuthCfg().getInstId().trim(), txnInfo.getSrcTxnAuthCfg().getMsgSrcId().trim(), txnInfo.getSrcTxnAuthCfg().getTransChannelId().trim());
            }
        }
        if (null == srcChannelInfo) {
            rglog.error("交易渠道<{}>的细分渠道<{}>未配置或已停用！", txnInfo.getSrcTxnAuthCfg().getMsgSrcId(), txnInfo.getSrcTxnAuthCfg().getTransChannelId());
            bizResponse.setRespCode(RespCodeEnum.SEC_PLAN_NOEXIT.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.SEC_PLAN_NOEXIT.getRespDesc());
            return bizResponse;
        }
        rglog.debug("srcChannelInfo值为:<{}>", JSON.toJSONString(srcChannelInfo));

        //获取安全计划信息
        SecPlanInfoMapper secPlanInfoMapper = new SecPlanInfoMapperImpl();
        String secPlanType = OpmsParamConstant.VERIFY_CERT_TYPE;
        SecPlanInfo secPlanInfo = secPlanInfoMapper.selectSecPlanInfoByPrimaryKey(instId, srcChannelInfo.getSecPlanId(), secPlanType);
        if (secPlanInfo == null) {
            rglog.info("安全计划信息获取为空");
            bizResponse.setRespCode(RespCodeEnum.SEC_PLAN_NOEXIT.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.SEC_PLAN_NOEXIT.getRespDesc());
            return bizResponse;
        } else if (!AppParamConstant.YES.equals(secPlanInfo.getSecPlanStatus())) {
            rglog.info("安全计划信息安全计划状态异常:<{}>", secPlanInfo.getSecPlanStatus());
            bizResponse.setRespCode(RespCodeEnum.SEC_PLAN_STATUS_FALSE.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.SEC_PLAN_STATUS_FALSE.getRespDesc());
            return bizResponse;
        }

        //获取证书信息
        String certIndex = instId + srcChannelInfo.getSecPlanId() + secPlanType;
        CertInfoMapper certInfoMapper = new CertInfoMapperImpl();
        CertInfo certInfo = certInfoMapper.selectCertInfoByPrimaryKey(certIndex);
        if (certInfo == null) {
            rglog.info("获取证书信息失败,certIndex:<{}>", certIndex);
            bizResponse.setRespCode(RespCodeEnum.CERT_STATUS_INVALID.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.CERT_STATUS_INVALID.getRespDesc());
            return bizResponse;
        } else if (AppParamConstant.NO.equals(certInfo.getKeyStatus())) {
            rglog.info("证书状态无效,certIndex:<{}>,keyStatus:<{}>", certIndex, certInfo.getKeyStatus());
            bizResponse.setRespCode(RespCodeEnum.CERT_STATUS_INVALID.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.CERT_STATUS_INVALID.getRespDesc());
            return bizResponse;
        }

        //获取公钥
        String pubKey;
        if (OpmsParamConstant.STR_TWO.equals(certInfo.getCertSaveType())) {
            rglog.info("证书以文件的方式存放，certIndex:<{}>,certSavePath:<{}>", certIndex, certInfo.getCertSavePath());
            try {
                pubKey = FileUtils.readFileToString(new File(certInfo.getCertSavePath()), Charset.defaultCharset());
            } catch (IOException e) {
                rglog.error("读取证书文件异常:{}", e.getMessage());
                bizResponse.setRespCode(RespCodeEnum.SYSTEM_ERROR.getRespCode());
                bizResponse.setRespDesc(RespCodeEnum.SYSTEM_ERROR.getRespDesc());
                return bizResponse;
            }
        } else {
            pubKey = certInfo.getCertValue();
        }

        //返回应答内容
        GetPublicKeyResponse response = new GetPublicKeyResponse();
        response.setPublicKey(pubKey);
        response.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        response.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setResult(response);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        GetPublicKeyResponse publicKeyResponse = (GetPublicKeyResponse) bizResponse.getResult();
        ConvertUtil.convertInput(publicKeyResponse);
    }
}
